//
//  EFPageCollectionMenu.m
//  MyCollectionView
//
//  Created by xinqing on 15/9/14.
//  Copyright (c) 2015年 pansoft. All rights reserved.
//

#import "EFPageCollectionMenu.h"
#import "PlistUtil.h"
#import "ViewControllerManager.h"
#import "EFMessageService.h"
#import "ThemeKit.h"

#define LAYOUT_HEIGHT 90
#define LAYOUT_WIDTH 50
#define SCROLL_DIRECTION UICollectionViewScrollDirectionVertical
#define PAGE_CONTROL_HEIGHT 10

@implementation EFPageCollectionMenu{
    UICollectionViewFlowLayout *_flowLayout;
    UIPageControl   *_pageControl;
    NSDictionary    *_checkDict;//plist
    NSMutableArray  *_stubObjects;
    BOOL            isUnSaveToPlist;
    JFMessageManager*_messageManager;
    NSInteger       myBadge;
}

-(void)createTheme {
    _collectionView.theme_backgroundColor = [UIColor theme_colorForKey:@"viewBackgroud" ];
}

//配置在当前界面
-(NSInteger)myBadgeWith:(NSDictionary *)dic {
    NSInteger checkBadge = 0;
    NSArray *allkey = [dic allKeys];
    for (NSString *key in allkey) {
        //task
        for (NSInteger i = 0; i < _stubObjects.count; i++) {
            StubObject *stub = _stubObjects[i];
            if ([[stub getID] isEqualToString:key] && [stub getStringForKey:@"applyId" withDefaultValue:nil] && [[dic objectForKey:key] integerValue] == 1) {
                checkBadge += [[[EFMessageService sharedMessageService].menuMap objectForKey:[stub getStringForKey:@"applyId" withDefaultValue:nil]] integerValue];
            }
        }
    }
    return checkBadge;
}

//没有配置在当前界面
-(NSInteger)otherBadgeWith:(NSDictionary *)dic {
    NSInteger checkBadge = 0;
    NSArray *allkey = [dic allKeys];
    for (NSString *key in allkey) {
        //task
        for (NSInteger i = 0; i < _stubObjects.count; i++) {
            StubObject *stub = _stubObjects[i];
            if ([[stub getID] isEqualToString:key] && [stub getStringForKey:@"applyId" withDefaultValue:nil] && [[dic objectForKey:key] integerValue] == 0) {
                checkBadge += [[[EFMessageService sharedMessageService].menuMap objectForKey:[stub getStringForKey:@"applyId" withDefaultValue:nil]] integerValue];
            }
        }
    }
    return checkBadge;
}

-(instancetype)initWithFrame:(CGRect)frame datas:(NSMutableArray *) stubObjects{
    self = [super initWithFrame:frame];
    if (self) {
        self.columnCount = 4;
        self.rowCount = 2;
        _checkDict = [PlistUtil getPLlistDicWitName:@"ConfigMenu.plist"];
        //过滤出选中的Items
        _items = [[NSMutableArray alloc] init];
        _stubObjects = stubObjects;
        NSInteger other = [self otherBadgeWith:_checkDict];
        [self filtrateItems:stubObjects];
        myBadge = [self myBadgeWith:_checkDict];
        [self setBackgroundColor:[UIColor clearColor]];
        
        _cellImageWidth = 50;
        _cellImageHeight = 50;
        _cellTitleHeight = 20;
        _cellTitleFontSize = 16;
        _cellTitleTextColor = [UIColor blackColor];
        _cellBackgroudColor = [UIColor clearColor];
        
        _pageIndicatorTintColor = [UIColor colorWithRed:0 green:0 blue:255 alpha:0.3];
        _currentPageIndicatorTintColor = [UIColor orangeColor];
        
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - PAGE_CONTROL_HEIGHT) collectionViewLayout:_flowLayout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.pagingEnabled = YES;//翻页
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.layer.borderWidth = -0.5;
        [self addSubview:_collectionView];
        
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(receiveNotification:) name:@"selectCollectionMenuNotification" object:nil];
        
        [self createTheme];
    }
    return self;
}

//注册方法
- (void) receiveNotification:(NSNotification*) notification
{
    _checkDict = [notification object];//获取到传递的对象
    NSInteger newMybadge = [self myBadgeWith:_checkDict];
    
    if (!(myBadge == newMybadge)) {
        MainTabBarController *tab = [ViewControllerManager getMainTabbarController];
        NSInteger oldBadge =  [[tab.tabBar.items objectAtIndex:2].badgeValue integerValue];
        oldBadge = oldBadge+(newMybadge-myBadge);
        if (oldBadge > 0 ) {
            [[tab.tabBar.items objectAtIndex:2] setBadgeValue:[NSString stringWithFormat:@"%ld",oldBadge]];
        }else {
            [[tab.tabBar.items objectAtIndex:2] setBadgeValue:nil];
        }
        
    }
    myBadge = newMybadge;
    [self refresh];
    
}

#pragma -mark 过滤出选中的Items
-(NSMutableArray *)filtrateItems:(NSMutableArray *) stubObjects{
    [_items removeAllObjects];
    isUnSaveToPlist = NO;
    for (StubObject *stub in stubObjects) {
        if ([self itemIsChecked:stub]) {
            [_items addObject:stub];
        }
    }
    //如果isUnSaveToPlist为YES 用stubObjects的数据。
    if (isUnSaveToPlist) {
        _items = [NSMutableArray arrayWithArray:stubObjects];
        return _items;
    }
    return  _items;
}

-(void)myBadge {
    
}

#pragma -mark 刷新
-(void)refresh{
    //    _checkDict = [PlistUtil getPLlistDicWitName:@"ConfigMenu.plist"];
    [self filtrateItems:_stubObjects];
    [self reloadData];
}

#pragma -mark 判断checked
-(BOOL)itemIsChecked:(StubObject *)stubObject{
    //如果是 “更多” 直接返回yes
    NSString *viewType = [stubObject getStringForKey:@"viewType" withDefaultValue:@""];
    if ([viewType isEqualToString:@"menuMore"]) {
        return YES;
    }
    //if plist 有值，从 plist 读取数据
    //else 从 stubObject 中读取数据
    BOOL isChecked;
    if(_checkDict != nil && _checkDict.count >0){
        NSString *isCheckedStr = [_checkDict objectForKey:[stubObject getID]];
        //如果出现stubObject中的数据未保存到ConfigMenu.plist中的情况 则isUnSaveToPlist为YES
        if (isCheckedStr == nil) {
            isUnSaveToPlist = YES;
        }
        isChecked = [isCheckedStr boolValue];
    }else{
        isChecked = [[stubObject getStringForKey:@"checked" withDefaultValue:@"0"] boolValue];
    }
    return isChecked;
}

#pragma -mark 2 创建组件
-(void)creationComplete{
    if (_flowLayout) {
        //！！！ cell的横向间距
        _flowLayout.minimumInteritemSpacing = 0;
        //        _flowLayout.minimumLineSpacing = 0;
        _flowLayout.itemSize = CGSizeMake(self.frame.size.width / _columnCount , _collectionView.frame.size.height / _rowCount );
        [_flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
    }
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[EFPageCollectionMenuCell class] forCellWithReuseIdentifier:@"CollectionViewIdentifier"];
    
    
}

#pragma -mark section
-(NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    //每页个数
    NSInteger pageCount = _columnCount * _rowCount;
    //页数
    NSInteger pages = ceil(((double)_items.count)/pageCount);
    [self addPageControlWithCount:pages];
    NSLog(@"items总数：%d,页数：%d",_items.count,pages);
    return pages * _columnCount;
}

#pragma -mark items
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _rowCount;
}

#pragma -mark - cell 菜单相关
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EFPageCollectionMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewIdentifier" forIndexPath:indexPath];
    
    if(cell.imageWidth == 0 && cell.imageHeight == 0 && cell.titleHeight == 0){
        cell.imageWidth = _cellImageWidth;
        cell.imageHeight = _cellImageHeight;
        cell.titleHeight = _cellTitleHeight;
        cell.titleFontSize = _cellTitleFontSize;
        cell.titleColor = _cellTitleTextColor;
        cell.backgroundColor = _cellBackgroudColor;
        [cell creationComplete];
    }
    NSInteger index = [self getIndexByIndexPath:indexPath];
    cell.indicateCount = 0;
    if (index < _items.count) {
        StubObject *currentStubObject = [_items objectAtIndex:index];
        
        //1.根据EFMessageService的treemap和menuMap  设置badgevalue
        NSArray  *appArray = [[currentStubObject getStringForKey:@"applyId" withDefaultValue:nil] componentsSeparatedByString:@";"];
        if (appArray) {
            //根据EFMessageService的menuMap 赋值badgevalue
            int unreadCount = 0;
            for (NSString *applyID in appArray) {
                unreadCount += [[[EFMessageService sharedMessageService].menuMap objectForKey:applyID] integerValue];
            }
            if(unreadCount>0) {
                cell.indicateCount = unreadCount;
            }
            
        }
        //
        for (NSString *apply in appArray) {
            NSMutableArray *sonArray = [[NSMutableArray alloc]init];
            if ([[EFMessageService sharedMessageService].viewMap objectForKey:apply]) {
                sonArray = [[EFMessageService sharedMessageService].viewMap objectForKey:apply];
            }
            [sonArray addObject:cell];
            [[EFMessageService sharedMessageService].viewMap setObject:sonArray forKey:apply];
        }
        
        NSString *imageUrl = [currentStubObject getStringForKey:@"menuIcon" withDefaultValue:@""];
        cell.imagePath = imageUrl;
        cell.title = [currentStubObject getCaption];
    }else{
        cell.image = nil;
        cell.title = nil;
        cell.indicateCount = 0;
    }
    return cell;
}

#pragma -mark 定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma -mark 点击调用delegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //调用delegate
    if (_pageCollectionMenuDelegate != nil && [_pageCollectionMenuDelegate respondsToSelector:@selector(pageCollectionMenu:didSelectItemAtIndex:)]) {
        
        NSInteger index = [self getIndexByIndexPath:indexPath];
        if(index < _items.count)
            [_pageCollectionMenuDelegate pageCollectionMenu:self didSelectItemAtIndex:index];
    }
}

//- (void)clearBadgeAction:(NSIndexPath *)indexPath{
//    NSInteger index = [self getIndexByIndexPath:indexPath];
//    if (index < _items.count) {
//        StubObject *currentStubObject = [_items objectAtIndex:index];
//        NSString *applyId = [currentStubObject getStringForKey:@"applyId" withDefaultValue:@""];
//        if (applyId) {
//            //清除item角标
//            [_messageManager unreadZeroWithUserID:[applyId intValue] postType:postType_0];
//            [_items[index] setString:@"0" forAKey:@"count"];
//            [_collectionView reloadData];
//            //更新tab item角标
//            [self clearTabItemBadgeAction];
//        }
//    }
//}
//
//更新tab item角标
- (void)clearTabItemBadgeAction{
    //    MainTabBarController *tab = [ViewControllerManager getMainTabbarController];
    //    NSInteger appIndex = 2;
    //    //[MenuRootUtil viewTypeIndexInTabbarWithKey:@""];
    //    NSInteger appBadge = 0;
    //    for (NSUInteger i=0; i<_tagManager.appApplyIdArray.count; i++) {
    //        appBadge = appBadge + [_messageManager unreadCountWithUserID:[_tagManager.appApplyIdArray[i] intValue] postType:postType_0];
    //    }
    //    if (appBadge != 0) {
    //        if (appBadge <= 99) {
    //            [[tab.tabBar.items objectAtIndex:appIndex] setBadgeValue:[NSString stringWithFormat:@"%d",appBadge]];
    //        }else{
    //            [[tab.tabBar.items objectAtIndex:appIndex] setBadgeValue:[NSString stringWithFormat:@"99+"]];
    //        }
    //    }else{
    //        [[tab.tabBar.items objectAtIndex:appIndex] setBadgeValue:nil];
    //    }
}

#pragma -mark 根据indexPath，计算出index
-(NSInteger)getIndexByIndexPath:(NSIndexPath *)indexPath{
    //当前页
    NSInteger currentPage = indexPath.section/_columnCount;
    //坐标互换，计算出index
    NSInteger index = (indexPath.row +currentPage)*_columnCount + indexPath.section +currentPage*_columnCount*(_rowCount-2);
    return index;
}
#pragma -mark 清除右上角所有的指示
-(void)clearAllIndicate{
    for (StubObject *stub in _items) {
        [stub setString:@"0" forAKey:@"count"];
    }
    [_collectionView reloadData];
}

-(void)clearIndicateAtIndex:(NSInteger)index{
    StubObject *stub = [_items objectAtIndex:index];
    if (stub != nil) {
        [stub setString:@"0" forAKey:@"count"];
        [_collectionView reloadData];
    }
}
-(void)reloadData{
    [_collectionView reloadData];
}

#pragma -mark 添加UIPageControl
-(void)addPageControlWithCount:(NSInteger)count{
    if (_pageControl != nil) {
        [_pageControl removeFromSuperview];
    }
    CGRect bounds = _collectionView.frame;
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0,bounds.size.height + 1 , bounds.size.width, PAGE_CONTROL_HEIGHT - 1)];
    //    _pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    _pageControl.numberOfPages = count;
    _pageControl.currentPage = 0;
    _pageControl.hidesForSinglePage=YES;
    _pageControl.backgroundColor = self.cellBackgroudColor;
    _pageControl.pageIndicatorTintColor = _pageIndicatorTintColor;
    _pageControl.currentPageIndicatorTintColor = _currentPageIndicatorTintColor;
    
    [self addSubview:_pageControl];
}

#pragma mark 设置scrollview的代理
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGRect bound = self.frame;
    int page= (scrollView.contentOffset.x+(bound.size.width/2))/bound.size.width;
    //NSLog(@"%d",page);
    _pageControl.currentPage = page;
}

-(void)setPageIndicatorTintColor:(UIColor *)pageIndicatorTintColor{
    _pageIndicatorTintColor = pageIndicatorTintColor;
    _pageControl.pageIndicatorTintColor = _pageIndicatorTintColor;
}

-(void)setCurrentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor{
    _currentPageIndicatorTintColor = currentPageIndicatorTintColor;
    _pageControl.currentPageIndicatorTintColor = _currentPageIndicatorTintColor;
}

#pragma mark EFPageCollectionMenuCellDelegate
-(void)changePageMenuCellIndicateLabelText:(NSString *)text cellTitle:(NSString *)title{
    for (NSUInteger i = 0; i<_items.count; i++) {
        NSString *stuTitle = [_items[i] getCaption];
        if ([stuTitle isEqualToString:title]) {
            [_items[i] setString:text forAKey:@"count"];
            NSInteger section = i%_columnCount;
            NSInteger row = i/_columnCount;
            NSIndexPath *index = [NSIndexPath indexPathForRow:row inSection:section];
            [_collectionView reloadItemsAtIndexPaths:@[index]];
        }
    }
}

-(void)dealloc{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"selectCollectionMenuNotification" object:nil];
}
@end
